package com.varton;

import com.alibaba.fastjson.JSON;
import com.varton.demo.model.Company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App {
    //ORM(对象关系映射    Object Relation Mapping)
    //说的就是讲已经持久化的数据内容转换为一个Java对象
    //用Java对象来描述对象与对象之间的关系和数据内容

    //Hibernate MyBatis JPA  SpringJDBC

    //Hibernate 全自动档  不需要写一句SQL语句、烧油（牺牲性能）
    //MyBatis  手自一体（半自动） 支持单表映射，多表关联需要配置，轻量级一些
    //SpringJDBC  手动挡 包括SQL语句，映射都是要自己实现的（最省油的）

    //喜欢轻装上阵  Spring本来就是万能胶IOC/AOP/DI/MVC/JDBC/BigData/Cloud/Boot
    //因为Spring形成一个生态



    //为什么要自己写ORM框架
    //1、解决实际的业务问题（根据业务需要）
    //2、自定义需求，如果要直接第三方开源框架的话，需要进行二次开发
    //3、解决团队成员之间水平参差不齐的问题
    //4、可以实现统一的管理、监控、排错等等一系列底层操作


    public static void main( String[] args ){
//        System.out.println( "Hello World!" );
//        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-context.xml");
//        try{
//            //1.加载驱动类
//            Class.forName("com.mysql.jdbc.Driver");
//            //2.建立连接
//            Connection connection = DriverManager.getConnection("jdbc:mysql://121.201.97.113:3306/charge-pay?characterEncoding=UTF-8&useSSL=false","root","Zqit3503");
//            //3.创建语句集
//            PreparedStatement prepareStatement = connection.prepareStatement("select * from company where id = ?");
//            //4.执行语句集
//            prepareStatement.setInt(1,1);
//            ResultSet resultSet = prepareStatement.executeQuery();
//            //5.获取结果集
//            Company company = new Company();
//            while (resultSet.next()){
//                company.setId(resultSet.getInt(1));
//                company.setName(resultSet.getString(2));
//            }
//            //6.关闭结果集
//            resultSet.close();
//            connection.close();
//            System.out.println(JSON.toJSONString(company));
//        }catch (Exception e){
//            System.out.println(JSON.toJSONString(e));
//        }

        Company condition = new Company();
        condition.setId(1);
        List<Company> list = select(condition);
        System.out.println(JSON.toJSONString(list));
    }

    public static <T> List<T> select(T t){
        try{
            //1.加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            //2.建立连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://121.201.97.113:3306/charge-pay?characterEncoding=UTF-8&useSSL=false","root","Zqit3503");
            //3.创建语句集
            Class<?> tClass = t.getClass();
            List<Object> values = new ArrayList<Object>();
            Field[] fields = tClass.getDeclaredFields();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < fields.length; i++){
                fields[i].setAccessible(true);
                Object value = fields[i].get(t);
                if (value != null){
                    values.add(value);
                    builder.append(fields[i].getName()+"=?").append(" and ");
                }
            }
            String sql = "select * from company where "+builder.toString().substring(0,builder.lastIndexOf(" and "));
            PreparedStatement prepareStatement = connection.prepareStatement(sql);
            System.out.println("==>execute sql:"+sql);
            //4.执行语句集
            for (int i = 0; i < values.size(); i++){
                prepareStatement.setObject(i+1,values.get(i));
            }
            ResultSet resultSet = prepareStatement.executeQuery();
            //5.获取结果集
            List<T> tList = new ArrayList<T>();
            ResultSetMetaData data = resultSet.getMetaData();
            while (resultSet.next()){
                T instance = (T) tClass.newInstance();
                for (int i = 1; i <= data.getColumnCount();i++){
                    Field f = tClass.getDeclaredField(data.getColumnName(i));
                    f.setAccessible(true);
                    f.set(instance,resultSet.getObject(data.getColumnName(i)));
                }
                tList.add(instance);
            }
            //6.关闭结果集
            resultSet.close();
            connection.close();
            return tList;
        }catch (Exception e){
            System.out.println(JSON.toJSONString(e));
        }
        return null;
    }
}
